//
//  UserDeviceListVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/6/19.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "UserDeviceListVC.h"
#import "DeviceItemCell.h"
#import "DeviceDetailVC.h"

@interface UserDeviceListVC () <UITableViewDelegate, UITableViewDataSource> {
    int mStart;
}

@property(weak, nonatomic) IBOutlet UIButton *backBt;
@property(weak, nonatomic) IBOutlet UIButton *addBt;

@property(weak, nonatomic) IBOutlet UIView *topView;
@property(weak, nonatomic) IBOutlet UILabel *countLb;
@property(weak, nonatomic) IBOutlet UILabel *onlineLb;
@property(weak, nonatomic) IBOutlet UITableView   *tableView;

@property(strong, nonatomic) NSMutableArray   *dataSource;

@end

@implementation UserDeviceListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    self.dataSource = [[NSMutableArray alloc] init];
    [[self.backBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [[self.addBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceBindVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    self.topView.layer.cornerRadius = 12;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceItemCell" bundle:nil] forCellReuseIdentifier:@"DeviceItemCellID"];
    self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        self->mStart = 0;
        [self requestData];
    }];
    self.tableView.mj_footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        self->mStart = (int)self.dataSource.count;
        [self requestData];
    }];
}

- (void)requestData {
    // 设备列表
    [self showLoading:@""];
    NSDictionary *dic = @{@"start": [NSNumber numberWithInteger:mStart], @"length": [NSNumber numberWithInt:mLength]};
    [[[HttpRequest shareInstance] signGet:d_device_list map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        [self hideLoading];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([x[@"code"] intValue] == 200) {
            @try {
                if (x[@"data"]) {
                    int count = 0;
                    if (self->mStart == 0) {
                        [self.dataSource removeAllObjects];
                    }
                    for (NSDictionary *temp in x[@"data"]) {
                        NSError *error;
                        DeviceItem *deviceItem = [MTLJSONAdapter modelOfClass:[DeviceItem class] fromJSONDictionary:temp error:&error];
                        NSError *error2;
                        NSDictionary *temp2 = [temp objectForKey:@"deviceState"];
                        DeviceState *deviceState = nil;
                        NSArray *clients = nil;
                        NSArray *disk = nil;
                        RomUpgradePlan *romUpgradePlan = nil;
                        @try {
                            deviceState = [MTLJSONAdapter modelOfClass:[DeviceState class] fromJSONDictionary:temp2 error:&error2];
                        } @catch (NSException *exception) {
                            
                        }
                        NSError *error3;
                        NSError *error4;
                        if (isNil(temp2)) {
                            @try {
                                NSArray *temp3 = [temp2 objectForKey:@"clients"];
                                clients = [MTLJSONAdapter modelsOfClass:[Clinets class] fromJSONArray:temp3 error:&error3];
                                NSArray *temp4 = [temp2 objectForKey:@"disks"];
                                disk = [MTLJSONAdapter modelsOfClass:[Disks class] fromJSONArray:temp4 error:&error4];
                            } @catch (NSException *exception) {
                                
                            }
                        }
                        
                        NSError *error5;
                        @try {
                            NSDictionary *temp5 = [temp objectForKey:@"romUpgradePlan"];
                            romUpgradePlan = [MTLJSONAdapter modelOfClass:[RomUpgradePlan class] fromJSONDictionary:temp5 error:&error5];
                        } @catch (NSException *exception) {
                            
                        }
                        
                        if (!error) {
                            if (!error2 && deviceState) {
                                if (!error3 && clients) {
                                    deviceState.clients = clients;
                                }
                                if (!error4 && disk) {
                                    deviceState.disks = disk;
                                }
                                deviceItem.deviceState = deviceState;
                            }
                            if (!error5) {
                                deviceItem.romUpgradePlan = romUpgradePlan;
                            }
                            [self.dataSource addObject:deviceItem];
                            if ([deviceItem.deviceOnlineState boolValue]) {
                                count ++;
                            }
                        }
                    }
                    [self.tableView reloadData];
                    self.countLb.text = [NSString stringWithFormat:@"设备数量：%lu",(unsigned long)self.dataSource.count];
                    self.onlineLb.text = [NSString stringWithFormat:@"在线数量：%d",count];
                }
            } @catch (NSException *exception) {
                NSLog(@"error=%@",exception);
            }
        }
    } error:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self hideLoading];
    }];
}


#pragma mark UITableView delegate and datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([UIScreen mainScreen].bounds.size.width<=320) {
        return 70;
    }
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceItemCellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell performSelector:@selector(setModel:) withObject:self.dataSource[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (0<= indexPath.row && indexPath.row<self.dataSource.count) {
        DeviceItem *item = self.dataSource[indexPath.row];
        DeviceDetailVC *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"DeviceDetailVCID"];
        [vc setData:item];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
